#coding=utf-8
import random
import base64

def en_str(key,s):
    kar=bytearray(key.encode())
    klen=len(kar)
    bar=bytearray(s.encode())
    offset=random.randint(0,0xff)
    rs=bytearray()
    rs.append(offset)
    for idx,sc in enumerate(bar):
        k=idx % klen
        rs.append(((sc+offset) % 0xff) ^ (kar[k] & kar[-(k+1)]))
    return base64.urlsafe_b64encode(rs).decode()

def de_str(key,s):
    if not s:
        return ''
    kar=bytearray(key.encode())
    klen=len(kar)
    bar=bytearray(base64.urlsafe_b64decode(s))
    offset=bar[0]
    rs=bytearray()
    for idx,sc in enumerate(bar[1:]):
        k=idx % klen
        t=(sc ^ (kar[k] & kar[-(k+1)]))
        if t<=offset:
            t+=0xff - offset
        else:
            t-=offset
        rs.append(t)
    return rs.decode()

if __name__=='__main__':
    k='test'
    s='abcdefg韦'
    r=en_str(k,s)
    print(r)
    print(de_str(k,r))
